import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router'

import { Hero } from '../Hero/hero';
import { HeroService } from '../service/hero.service';


@Component({
	selector: 'hero-list',
	templateUrl: './hero-list.component.html',
	styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

	private title: string = '英雄之旅';
	private heroes: Hero[];
	private selectedHero: Hero;		//激活状态的英雄

	constructor(
		private HeroService: HeroService,
		private router: Router
	) { }

	ngOnInit(): void {
		this.getHeroes();
	}

	getHeroes(): void {
		this.HeroService.getHeroes()
			.then(heroes => this.heroes = heroes);	//英雄列表
	}

	onSelect(hero: Hero): void {
		this.selectedHero = hero;
	}

	goDetail(): void {
		this.router.navigate(['/detail', this.selectedHero.id]);
	}

	add(name: string): void {
		name = name.trim()	//去两边空白
		if (!name) { return; };
		this.HeroService.create(name)
			.then(hero => {
				this.heroes.push(hero);
				this.selectedHero = null;
			})
	}

	delete(hero: Hero): void {
		this.HeroService
			.delete(hero.id)
			.then( () =>{
				this.heroes = this.heroes.filter( h => h !== hero );
				if(this.selectedHero === hero){
					this.selectedHero =null;
				}
			} )
	}
}